package com.homer.gps.track;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnShowListener;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.homer.gps.track.adapters.StopsArrayAdapter;
import com.homer.gps.track.helper.UsefullStaff;
import com.homer.gps.track.persist.DatabaseHelper;
import com.homer.gps.track.persist.PlaceModel;
import com.homer.gps.track.persist.Repository;
import com.homer.gps.track.persist.RouteModel;
import com.homer.gps.track.persist.StopModel;
import com.homer.gps.track.persist.StopsHasPlacesModel;
import com.homer.gps.track.template.DefaultORMSherlockActivity;
import com.j256.ormlite.android.apptools.OpenHelperManager;

public class RouteEdit extends DefaultORMSherlockActivity {
	private static final int PLACES_SCREEN = 101;

	private TextView routeName, routeType, routeNote, routeStartPlace, routeStartDate, routeStartPlaceAddress;
	private TextView routeEndPlace, routeEndDate, routeEndPlaceAddress;
	private ImageView routeStartPlaceTypeIcon, routeEndPlaceTypeIcon;
	
	private RouteModel selectedRoute = null;
	private PlaceModel startPlace = null;
	
	private ListView stopsList;
	private StopsArrayAdapter stopsListAdapter;

	private Repository repository;
	private ViewGroup stoplayout;
	private boolean stoptracking = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);	
		setContentView(R.layout.route_edit);
		repository = super.getRepository(this);
		int selected_id = getIntent().getIntExtra("id", -1);
		stoptracking = getIntent().getBooleanExtra("stopTracking", false);
		if (selected_id != -1) {
			selectedRoute = repository.getRouteForId(selected_id);
		}	
		initActivity();
	}

	private void initActivity() {
		getSupportActionBar().setHomeButtonEnabled(true);
		routeName = (TextView) findViewById(R.id.route_name);
		routeType = (TextView) findViewById(R.id.route_type);
		routeNote = (TextView) findViewById(R.id.route_note);
		routeStartPlace = (TextView) findViewById(R.id.start_place);
		routeStartPlaceAddress = (TextView) findViewById(R.id.start_place_address);
		routeStartDate = (TextView) findViewById(R.id.route_start_date);
		routeStartPlaceTypeIcon = (ImageView) findViewById(R.id.start_place_type_icon);
		routeEndPlace = (TextView) findViewById(R.id.end_place);
		routeEndPlaceAddress = (TextView) findViewById(R.id.end_place_address);
		routeEndDate = (TextView) findViewById(R.id.route_end_date);
		
		if (selectedRoute == null) {
			getSupportActionBar().setTitle(R.string.title_route_new);
			routeStartDate.setText(UsefullStaff.getFormatedDateAndTime(new Date(), "dd/MM/yyyy"));
			//stoplayout = (ViewGroup) findViewById(R.id.stop_layout);
			//stoplayout.setVisibility(View.GONE);

		}else {
			getSupportActionBar().setTitle(R.string.title_route_edit);
			routeName.setText(selectedRoute.getName());
			String[] routeTypes = getResources().getStringArray(R.array.route_types);
			int routeTypePos = ((RouteModel)repository.getRouteForId(selectedRoute.getId())).getType();
			routeType.setText(routeTypes[routeTypePos]);
			routeNote.setText(selectedRoute.getNote());
			stopsList = (ListView) findViewById(R.id.stops_list);
			List<StopModel> otherStops = null;
			try {
				otherStops = repository.lookupStopsForRoute(selectedRoute, StopModel.STOP_TYPE_OTHER);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (otherStops != null) {
				stopsListAdapter = new StopsArrayAdapter(this, R.layout.stops_list_item, otherStops);
			}
			
			stopsList.setAdapter(stopsListAdapter);
		}		
	}

	public void onRouteValueClicked (View view) {
		View selectedView = view;
		TextView title = (TextView) view.findViewById(R.id.title);
		TextView value;
		switch (selectedView.getId()) {
		case R.id.name_layout:
			value = (TextView) view.findViewById(R.id.route_name);
			getInputDialog(view, title.getText(), value).show();
			break;
		case R.id.type_layout:
			value = (TextView) view.findViewById(R.id.route_type);
			getInputDialog(view, title.getText(), value).show();
			break;
		case R.id.route_note_layout:
			value = (TextView) view.findViewById(R.id.route_note);
			getInputDialog(view, title.getText(), value).show();
			break;
		default:
			break;
		}
	}

	public void onStartValueClicked (View view) {
		Intent i = new Intent(this, Places.class);
		i.putExtra("requestCode", true);
		startActivityForResult(i, PLACES_SCREEN);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		menu.add("Text")
		.setIcon(R.drawable.btn_check_buttonless_on)
		.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			return true;
		case 0:
			onSaveButtonClicked();
			return true;
		case 1:
			finish();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case PLACES_SCREEN:
			if (resultCode == Activity.RESULT_OK) {
				int selectedItemId = data.getIntExtra("selectedItemId", -1);
				if (selectedItemId > -1) {
					startPlace = repository.getPlaceForId(selectedItemId);
					routeStartPlace.setText(startPlace.getName().toString());
					routeStartPlaceAddress.setText(startPlace.getParsedAddress());
					routeStartPlaceTypeIcon.setImageResource(UsefullStaff.getPlaceTypeImageResource(startPlace.getType()));
					routeStartPlaceTypeIcon.setVisibility(View.VISIBLE);
				}
			}
			break;
		default:
			super.onActivityResult(requestCode, resultCode, data);
			break;
		}
	}

	private void onSaveButtonClicked(){
		if (routeName.getText().length() <= 0) {
			Toast.makeText(this, R.string.required_value, Toast.LENGTH_SHORT).show();
			routeName.requestFocus();
			routeName.setError(getString(R.string.required_value));
			return;
		}
		if (routeType.getText().length() <= 0) {
			Toast.makeText(this, R.string.required_value, Toast.LENGTH_SHORT).show();
			routeType.requestFocus();
			routeType.setError(getString(R.string.required_value));
			return;
		}
		RouteModel route = null;
		if (selectedRoute == null) {
			route = new RouteModel();
			route.setRunning(true);
		}else {
			route = selectedRoute;
		}
		
		final StopModel stop = new StopModel();
		//final StopsHasPlacesModel stophasHasPlace = new StopsHasPlacesModel();
		//		if (id != -1) {
		//			place.setId(id);
		//		}
		route.setName(routeName.getText().toString());
		List<String> types = Arrays.asList(getResources().getStringArray(R.array.route_types));
		route.setType(types.indexOf(routeType.getText()));
		route.setNote(routeNote.getText().toString());
		stop.setStartDateTime(new Date());
		stop.setType(StopModel.STOP_TYPE_START);
		repository.saveOrUpdateRoute(route);
		stop.setRoute(route);
		repository.saveOrUpdateStop(stop);
		repository.saveOrUpdateStopsHasPlaces(new StopsHasPlacesModel(stop, startPlace));
		
		Intent result = new Intent();
		result.putExtra("createdRouteId", route.getId());
		result.putExtra("stopTracking", stoptracking);
		setResult(RESULT_OK, result);
		finish();
	}

	private AlertDialog getInputDialog(final View view, final CharSequence title, final TextView value) {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle(title);
		alert.setMessage(null);

		final EditText input = new EditText(this);
		final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.route_types, android.R.layout.simple_list_item_single_choice);
		if (value.getId() == R.id.route_type) {
			alert.setSingleChoiceItems(adapter, 1, new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
				}
			});
		}else {	
			if (value.getInputType() != 0)
				input.setInputType(value.getInputType());
			if (value.getText().length() > 0)
				input.setText(value.getText());
			alert.setView(input);	
		}

		alert.setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {

				String text;
				if (value.getId() == R.id.route_type) {
					int selectedPosition = ((AlertDialog)dialog).getListView().getCheckedItemPosition();
					text = (String)adapter.getItem(selectedPosition);
				}else{
					text = input.getText().toString();
				}
				if (text.length() > 0) {
					value.setText(text);
				}
				else {
					value.setText("");
				}
			}
		});

		alert.setNegativeButton(getString(android.R.string.cancel), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				dialog.dismiss();
			}
		});

		AlertDialog dialog = alert.create();
		dialog.setOnShowListener(new OnShowListener() {

			@Override
			public void onShow(DialogInterface dialog) {
				if (value.getId() != R.id.route_type) {
					InputMethodManager inputMethodManager=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
					inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);
				}
			}
		});
		return dialog;
	}

	public static String getActualDateText() {
		String resDate;
		//SimpleDateFormat sdf = new SimpleDateFormat(format, LocaleDelegate.getPreferenceLocale(context));
		SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
		resDate = sdf.format(Calendar.getInstance().getTime());

		return resDate;
	}

	public static String getActualTimeText() {
		String resTime;
		//SimpleDateFormat sdf = new SimpleDateFormat(format, LocaleDelegate.getPreferenceLocale(context));
		SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
		resTime = sdf.format(Calendar.getInstance().getTime());

		return resTime;
	}

}
